import os

from rest_framework.viewsets import ViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from flow.models import *
from flow.serializer import *
from util.jwt_token import check_login
from util.qiniuyun_token import qiniu_token
from .serializer import *
from user.serializer import *
from django.conf import settings


# 获取七牛云token
class Qiniu(ViewSet):
    def qiniuyun(self, request):
        try:
            token = qiniu_token()
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "token": token})

        except Exception as e:
            print("错误", e)
            return Response({"code": 500, "msg": "失败"})


# 审批类型
class ApprovalView(ViewSet):

    # 获取审批类型
    @check_login
    def vetting_list(self, request):
        try:
            type = TypeModel.objects.filter(is_delete=0)
            type_ser = TypeSer(type, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": type_ser.data})
        except Expense as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 添加审批类型
    @check_login
    def vetting_add(self, request):
        name = request.data.get("name")
        lastervisename = request.data.get("lastrevisename")
        lastrevisetime = request.data.get("lastrevisetime")
        template = request.data.get("template")

        print('数据', request.data)

        if not all([name, lastervisename, lastrevisetime, template]):
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全"})

        type = TypeModel.objects.filter(name=name).count()
        if type != 0:
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "类别存在"})
        try:
            templates = Template.objects.filter(is_delete=0)
            template_ser = TemplateSer(templates, many=True).data
            for template_name in template_ser:
                if template_name.get("template_name") == template:
                    template = template_name.get("id")

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users, many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastervisename:
                    lastervisename = users_name.get("id")
            data = {
                "name": name,
                "lastervisename": lastervisename,
                "upd_time": lastrevisetime,
                "template_id": template
            }

            ser = TypeSer(data=data)
            ser.is_valid()

            TypeModel.objects.create(name=name, template_id=template, upd_time=lastrevisetime, lastervisename_id=lastervisename)
            return Response({"code": status.HTTP_200_OK, "msg": "添加成功"})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 修改审批类型
    def vetting_update(self, request, pk):
        try:
            name = request.data.get("name")
            lastervisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            template = request.data.get("template")
            print(request.data)

            templates = Template.objects.filter(is_delete=0)
            template_ser = TemplateSer(templates, many=True).data
            for template_name in template_ser:
                if template_name.get("template_name") == template:
                    template = template_name.get("id")

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users, many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastervisename:
                    lastervisename = users_name.get("id")

            data = {
                "name": name,
                "lastervisename": lastervisename,
                "upd_time": lastrevisetime,
                "template_id": template
            }

            ser = TypeSer(data=data)
            ser.is_valid()

            TypeModel.objects.filter(id=pk).update(name=name, template_id=template, upd_time=lastrevisetime,
                                                   lastervisename_id=lastervisename)
            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 获取单个审批类型
    def veetting_info(self, request, pk):
        try:
            type = TypeModel.objects.filter(id=pk, is_delete=False).first()
            ser = TypeSer(type)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 删除审批类型
    def veetting_delete(self, request, pk):
        try:
            type = TypeModel.objects.filter(id=pk, is_delete=False)
            type.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "成功"})
        except Exception as e:
            print("获取失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})


# 审批流程
class FlowView(ViewSet):
    # 获取审批流程
    @check_login
    def flow_list(self, request):
        try:
            flow = FlowModel.objects.filter(is_delete=0)
            flow_ser = FlowSer(flow, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_ser.data})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 添加审批流程
    @check_login
    def flow_add(self, request):
        try:
            name = request.data.get("name")
            state = request.data.get("state")
            lastrevisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            levels = request.data.get("levels")
            peocess = request.data.get("peocess")
            print(request.data)
            print(levels)

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users, many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastrevisename:
                    lastrevisename = users_name.get("id")
                    position_id = users_name.get("position")
            print("职位id", position_id)
            position = PositionModel.objects.get(id=position_id)
            position_ser = PositionSer(position).data
            print('position_ser', position_ser)
            data = {
                "flow_name": name,
                "currentvetting": lastrevisename,
                "is_enable": 1,
                "level": levels,
                "start_time": lastrevisetime,
                "peocess": peocess,
                "department": position_ser.get("department")
            }

            ser = FlowSer(data=data)
            ser.is_valid()
            flow = FlowModel.objects.create(flow_name=name, currentvetting_id=lastrevisename, level_id=levels,
                                            dept_id=position_ser.get("department"), peocess=peocess)
            # flow_ser = FlowSer(flow).data
            # flow_ser_id = flow_ser.get("id")
            # UserFlowNodeModel.objects.create(name_id=lastrevisename, flow_node_id=flow_ser_id)
            return Response({"code": status.HTTP_200_OK, "msg": "添加成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 获取单个审批流程
    def flow_info(self, request, pk):
        try:
            flow = FlowModel.objects.filter(id=pk, is_delete=False).first()
            flow_ser = FlowSer(flow)
            return Response({"code": status.HTTP_200_OK, "msg": "获取成功", "data": flow_ser.data})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 修改单个审批流程
    def flow_update(self, request, pk):
        try:
            name = request.data.get("name")
            state = request.data.get("state")
            lastrevisename = request.data.get("lastrevisename")
            lastrevisetime = request.data.get("lastrevisetime")
            levels = request.data.get("levels")
            peocess = request.data.get("peocess")
            print(request.data)
            print(levels)

            if FlowModel.objects.filter(id=pk).count() == 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "此id不存在"})

            users = UserModel.objects.filter(is_delete=0)
            users_ser = UserSer(users, many=True).data
            for users_name in users_ser:
                if users_name.get("name") == lastrevisename:
                    lastrevisename = users_name.get("id")
                    position_id = users_name.get("position")
            print("职位id", position_id)
            position = PositionModel.objects.get(id=position_id)
            position_ser = PositionSer(position).data
            print(position_ser)

            data = {
                "flow_name": name,
                "currentvetting": lastrevisename,
                "is_enable": 1,
                "level": levels,
                "start_time": lastrevisetime,
                "peocess": peocess,
                "department": position_ser.get("department")
            }

            ser = FlowSer(data=data)
            ser.is_valid()
            flow = FlowModel.objects.filter(id=pk)
            flow.update(flow_name=name, currentvetting_id=lastrevisename, level_id=levels, dept_id=position_ser.get("department"), peocess=peocess)
            return Response({"code": status.HTTP_200_OK, "msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})

    # 删除单个审批流程
    def flow_delete(self, request, pk):
        try:
            FlowModel.objects.filter(id=pk).update(is_delete=1)
            return Response({"code": status.HTTP_200_OK, "msg": '删除成功'})
        except Exception as e:
            print("删除", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})


# 请假模板
class LeaveViews(APIView):
    def post(self, request):
        try:
            leavetime = request.data.get("leavetime")
            leavecause = request.data.get("leavecause")
            leavetype = request.data.get("leavetype")
            print('数据', request.data)

            type = Leave_Type.objects.filter()
            type_ser = LeaveTypeSer(type, many=True).data
            for type_name in type_ser:
                if type_name.get("type_name") == leavetype:
                    leavetype = type_name.get("id")
            data = {
                "cause": leavecause,
                "leave_type": leavetype,
                "leavetime": leavetime,
                "type": 1,
            }
            ser = LeaveSer(data=data)
            ser.is_valid()

            Leave.objects.create(cause=leavecause, begin_time=leavetime, leave_type_id=leavetype, type_id=1)
            return Response({"code": status.HTTP_200_OK, "msg": "添加成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "服务器错误"})


# 借款模板
class LoanViews(APIView):
    def post(self, request):
        try:
            loantime = request.data.get("loantime")
            loancause = request.data.get("loancause")
            maney = request.data.get("money")
            print(request.data)

            data = {
                "begin_time": loantime,
                "cause": loancause,
                "money": maney,
                "type": 2,
            }

            ser = MoneySer(data=data)
            ser.is_valid()
            Money.objects.create(begin_time=loantime,cause=loancause,money=maney, type_id=2)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 出差模板
class TravelViews(APIView):
    def post(self, request):
        try:
            traveltime = request.data.get("traveltime")
            destination = request.data.get("destination")
            travelcause = request.data.get("travelcause")
            travelentourage = request.data.get("travelentourage")
            print(request.data)

            data = {
                "cause": travelcause,
                "begin_time": traveltime,
                "address": destination,
                "peer":travelentourage,
                "type": 2,
            }
            ser = TravelSer(data=data)
            ser.is_valid()
            Travel.objects.create(cause = travelcause,begin_time= traveltime,address= destination,peer=travelentourage,type_id=3)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print("失败原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 转正模板
class PositiveViews(APIView):
    def post(self, request):
        try:
            positivetime = request.data.get("positivetime")
            appraisal = request.data.get("appraisal")
            print(request.data)
            data = {
                "cause": appraisal,
                "begin_time": positivetime,
                "type": 4,
            }
            ser = FormalSer(data=data)
            ser.is_valid()
            Formal.objects.create(cause=appraisal, type_id=4, begin_time=positivetime)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print("失败原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 用车模板
class BycarViews(APIView):
    def post(self, request):
        try:
            bycartime = request.data.get("bycartime")
            bycarstart = request.data.get("bycarstart")
            bycardestination = request.data.get("bycardestination")
            bycartype = request.data.get("bycartype")
            bycarcode = request.data.get("bycarcode")

            vehicle = Vehicle.objects.all()
            vehicle_ser = VehicleSer(vehicle, many=True).data
            plate = Plate.objects.all()
            plate_ser = PlateSer(plate, many=True).data

            for vehicle in vehicle_ser:
                if vehicle.get("vehicle_name") == bycartype:
                    bycartype = vehicle.get("id")

            for plate in plate_ser:
                if plate.get("plate_name") == bycarcode:
                    bycarcode = plate.get("id")

            data = {
                "begin_time":bycartime,
                "start":bycarstart,
                "end":bycardestination,
                "vehicle":bycartype,
                "plate":bycarcode,
                "type":5
            }

            ser = CarSer(data=data)
            ser.is_valid()
            Car.objects.create(begin_time=bycartime,start=bycarstart,end=bycardestination,vehicle_id=bycartype,plate_id=bycarcode,type_id=5)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print("失败原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 报销模板
class ReimbursementViews(APIView):
    def post(self, request):
        try:
            reimbursedsum = request.data.get("reimbursedsum")
            reimbursedreason = request.data.get("reimbursedreason")
            materials = request.data.get("materials")
            print(request.data)
            data = {
                "cause": reimbursedreason,
                "voucher": materials,
                "money": reimbursedsum,
                "type": 6,
            }
            ser = FormalSer(data=data)
            ser.is_valid()
            Expense.objects.create(cause=reimbursedreason, type_id=6, voucher=materials, money=reimbursedsum)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print("失败原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 材料
class StuffVise(ViewSet):

    # 新增材料
    @check_login
    def stuff_add(self, request):

        # 接受前端数据
        file = request.data.get("materialname")
        path = request.data.get("materialurl")

        # 判断结尾是否是以.xlsx和.elsx 结尾的
        if not re.search(r"\.(xlsx|elsx)$", file.name):
            return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "只能上传 xlsx 和 elsx 格式的文件哦!!"})

        # 拼接
        filepath = os.path.join(settings.STATICFILES_DIRS[0])
        print('----', filepath)
        filename = filepath + file.name
        print("filename", filename)

        # 判断材料是否存在
        stuff = StuffModel.objects.filter(name=file.name, is_delete=False).first()
        if stuff:
            return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "材料已经存在"})

        print('/////', filename)
        # 打开文件 写入
        with open(filename, "wb") as f:
            f.write(file.file.read())

        print("file.name:", file.name)
        user = UserModel.objects.get(id=self._cuser.id)
        user.avatar_url = file.name
        user.save()

        StuffModel.objects.create(name=file.name, path=path)

        return Response({
            'code': '200',
            'msg': '上传成功',
            'data': file.name
        })

    # 获取全部材料
    @check_login
    def stuff_list(self, request):
        try:
            stuff =StuffModel.objects.all()
            ser = StuffSer(stuff, many=True)
            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 修改材料
    @check_login
    def stuff_update(self, request, pk):
        name = request.data.get("materialname")
        path = request.data.get("materialurl")

        try:
            stuff = StuffModel.objects.filter(id=pk, is_delete=False)
            if not stuff:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此材料"})

            if name:
                stuff.update(name=name)
            if path:
                stuff.update(path=path)
            return Response({"code": status.HTTP_200_OK, "msg": "成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 删除材料
    @check_login
    def stuff_delete(self, request, pk):
        try:
            stuff = StuffModel.objects.filter(id=pk, is_delete=False)
            if not stuff:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此材料 "})

            stuff.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "msg": "删除成功"})
        except Exception as e:
            print("删除失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 获取材料
    def stuff_info(self, request, pk):
        try:
            stuff = StuffModel.objects.filter(id=pk, is_delete=False).first()
            if not stuff:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "没有此材料 "})
            ser = StuffSer(stuff)

            return Response({"code": status.HTTP_200_OK, "msg": "成功", "data": ser.data})
        except Exception as e:
            print("失败", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "失败"})

    # 搜索材料
    @check_login
    def search(self, request):
        try:
            name = request.data.get("name")
            menu = StuffModel.objects.filter(name=name).first()
            ser = StuffSer(menu)
            return Response({"code": status.HTTP_200_OK, "msg": "搜索成功", "data": ser.data})
        except Exception as e:
            print("搜索失败的原因", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "搜索失败"})


